import axios from 'axios'
import { Toast, Dialog } from 'vant'
import { apiPrefix } from '@/settings'

// 提示
Toast.allowMultiple(false)
let count = 0
function loading(cnf) {
  if (cnf && cnf.loading === false) return
  count++
  Toast.loading({
    message: cnf.message || '加载中...',
    forbidClick: true,
    loadingType: 'spinner',
    duration: 0
  })
}
function clear(cnf) {
  if (cnf && cnf.loading === false) return
  count--
  if (count <= 0) {
    Toast.clear()
    count = 0
  }
}
const excludeApis = ['/data-dict/app', '/ucenter/api', '/select-service/app'] // 外部api地址

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 10000 // request timeout
})

service.interceptors.request.use(
  async config => {
    excludeApis.forEach(api => {
      if (config.url.indexOf(api) === 0) {
        config.baseURL = process.env.VUE_APP_BASE_API.replace(apiPrefix, '')
      }
    })

    const { token } = await window.nativeHandler()
    config.headers['Authorization'] = token

    loading(config)
    return config
  },
  error => {
    // console.log(error) // for debug
    return Promise.reject(error)
  }
)

service.interceptors.response.use(
  response => {
    const resConfig = response.config
    clear(resConfig)
    const res = response.data
    const status = Number(response.status) || 200
    const message = res.msg || '未知原因，请联系管理员'

    if (status !== 200 || res.success === 0) {
      if (resConfig.errorShow !== false) {
        Toast(message)
      }
      return Promise.reject(message)
    }

    if (resConfig.responseType === 'blob') {
      return response
    }
    return res
  },
  error => {
    const errorConfig = error.config
    clear(errorConfig)
    const res = error.response
    if (res) {
      const status = Number(res.status) || 200
      if (status === 401 || (res?.data && (res.data.code === 401 || res.data.code === '401'))) {
        Toast('登录已失效，请重新登录。(您的账号可能已在别处登录，请妥善保存密码，勿与他人共用账号。')
      } else {
        if (errorConfig.errorShow !== false) {
          Toast(error.message)
        }
      }
    } else {
      Toast('网络服务异常')
    }
    return Promise.reject(error)
  }
)

export default service
